"""
Case Type   : datakit并行安装数据库
Case Name   : 创建并行安装任务，点击备节点安装用户，显示所有已添加的用户
Create At   : 2025/06/09
Owner       : @ningyali
Description :
    1.导入备服务器
    2.备节点添加用户
    3.获取备节点安装用户列表
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import os
import subprocess
import unittest

import requests
from testcase.utils.Common import Common
from testcase.utils.CommonDatakit import CommonDatakit
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from testcase.utils.datakit_api.BaseOpsApi import BaseOpsApi
from testcase.utils.datakit_api.CommonApi import CommonApi
from yat.test import Node
from yat.test import macro


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.sta1_node_root = Node('Standby1Root')
        self.host_list = [self.sta1_node_root]
        self.user_lists = [f'Batch_0021_{i}' for i in range(1, 11)]

        text = '----prestep1:获取token expect:执行成功----'
        self.log.info(text)
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotIn("error", self.token.lower(), f'执行失败:{text}')

        self.com_api = CommonApi(self.token)
        self.base_ops_api = BaseOpsApi(self.token)
        self.datakit_sh = CommonDatakit(self.token)
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token}

    def test_batch_installation(self):
        text = '----step1:导入备服务器 expect:成功----'
        self.log.info(text)
        self.datakit_sh.import_host(self.host_list)

        text = '----step2:备节点添加用户 expect:成功----'
        self.log.info(text)
        res1 = self.com_api.get_host_page(name=self.sta1_node_root.ssh_host)
        self.sta1_host_id = res1.json()['rows'][0]['hostId']
        for user in self.user_lists:
            data = {"hostId": self.sta1_host_id,
                    "username": user,
                    "password": f"{macro.COMMON_PASSWD}"}
            res2 = self.com_api.post_hostUser(data)
            self.log.info(f'res2.json():{res2.json()}')
            self.assertEqual(200, res2.json()['code'], '添加用户失败')

        text = '----step3:获取备节点安装用户列表 expect:成功----'
        self.log.info(text)
        api = f'/plugins/base-ops/clusterTask/hostUser/{self.sta1_host_id}'
        response = requests.get(url=self.base_ops_api.ip + api,
                                headers=self.headers, verify=False)
        self.log.info(f'response.text:{response.text}')
        for user in self.user_lists:
            self.assertIn(user, response.text, f'执行成功:{text}')

    def tearDown(self):
        text = '----step4:清理环境 expect:成功----'
        self.log.info(text)
        self.datakit_sh.delete_host()
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
